# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import *
from django.views.decorators.csrf import csrf_exempt
from django.template import RequestContext, Template
from django.utils.encoding import smart_str, smart_unicode
from xml.etree import ElementTree as etree
from resp_douban_book import douban_search_book
from resp_templates import *
from private_key import *
import hashlib
import time
import json
import re

@csrf_exempt
def weixin(request):
    try:
        return _weixin(request)
    except Exception as e:
        err_msg = '(server error):%s' % str(e)
        print err_msg
        return HttpResponseServerError(err_msg)

def _weixin(request):
    if request.method == 'GET':
        echostr = request.GET.get('echostr', '')
        if verification(request) and echostr is not None:
            return HttpResponse(echostr)
        return HttpResponseBadRequest('bad request')
    else:
        if not verification(request):
            return HttpResponseBadRequest('bad request')
        msg = parse_msg(request)
        return resp_dispatcher(msg)

def verification(request):
    '''
    接入和消息推送都需要做校验
    '''
    signature = request.GET.get('signature', '')
    timestamp = request.GET.get('timestamp', '')
    nonce = request.GET.get('nonce', '')
    token = 'asdf1234qwer' #注意要与微信公众帐号平台上填写一致
    tmplist = [token, timestamp, nonce]
    tmplist.sort()
    tmpstr = ''.join(tmplist)
    hashstr = hashlib.sha1(tmpstr).hexdigest()
    if hashstr == signature:
        return True
    return False

def parse_msg(request):
    xmlstr = smart_str(request.body)
    root = etree.fromstring(xmlstr)
    msg = {}
    for child in root:
        msg[child.tag] = child.text
    return msg

def resp_dispatcher(msg):
    if msg['MsgType'] == 'event' and msg['Event'] == 'subscribe':
        return HttpResponse(resp_txt(msg, HELP_INFO))
    elif msg['MsgType'] == 'text':
        return resp_disp_text(msg)
    elif msg['MsgType'] == 'image':
        return resp_disp_picture(msg)
    elif msg['MsgType'] == 'voice':
        return resp_disp_voice(msg)
    elif msg['MsgType'] == 'video':
        return resp_disp_video(msg)
    elif msg['MsgType'] == 'shortvideo':
        return resp_disp_shortvideo(msg)
    elif msg['MsgType'] == 'location':
        return resp_disp_location(msg)
    elif msg['MsgType'] == 'link':
        return resp_disp_link(msg)
    else:
        return HttpResponse(resp_txt(msg, HELP_INFO))

def resp_disp_text(msg):
    content = msg['Content'].strip()
    if content in (u'?', u'？'):
        return HttpResponse(resp_txt(msg, HELP_INFO))
    elif content in ('TDM', 'tdm'):
        art_list = []
        tdm_logo_url = 'http://115.182.69.8:8103/static/pic/tdm_logo.png'
        art_item = ('title', 'description', 'picurl', 'url')
        art_list.append(dict(zip(art_item, (u'TDM教学管理系统', '', tdm_logo_url, 'http://115.182.69.8:8103/tdm/login/'))))
        art_list.append(dict(zip(art_item, (u'TDM电源管理', '', tdm_logo_url, 'http://115.182.69.8:8103/tdm/power/'))))
        art_list.append(dict(zip(art_item, (u'TDM网络管理', '', tdm_logo_url, 'http://115.182.69.8:8103/tdm/network/'))))
        art_list.append(dict(zip(art_item, (u'TDM服务器管理', '', tdm_logo_url, 'http://115.182.69.8:8103/tdm/server'))))
        art_list.append(dict(zip(art_item, (u'TDM移动管理', '', tdm_logo_url, 'http://115.182.69.8:8103/tdm/mdm'))))
        art_list.append(dict(zip(art_item, (u'TDM考勤管理', '', tdm_logo_url, 'http://115.182.69.8:8103/tdm/acard'))))
        return HttpResponse(resp_articles(msg, art_list))
    elif content.find(u'查书') == 0:
        book_match = re.match(u'查书 (.*)', content)
        if not book_match:
            return HttpResponse(resp_txt(msg, content+' 格式不正确'))
        books = douban_search_book(book_match.groups()[0])
        return HttpResponse(resp_articles(msg, books))
    elif content in ("jssdk", "sdk"):
        return HttpResponse(resp_txt(msg, WXJS_TPL))
    elif content in ("game", "GAME", "Game"):
        return HttpResponse(resp_txt(msg, GAME_TPL))
    else:
        return HttpResponse(resp_txt(msg, msg['Content']))

def resp_disp_picture(msg):
    #暂时不支持图像消息
    print msg
    return HttpResponse(resp_txt(msg, HELP_INFO))

def resp_disp_voice(msg):
    print msg
    return HttpResponse(resp_txt(msg, HELP_INFO))

def resp_disp_video(msg):
    print msg
    return HttpResponse(resp_txt(msg, HELP_INFO))

def resp_disp_shortvideo(msg):
    print msg
    return HttpResponse(resp_txt(msg, HELP_INFO))

def resp_disp_location(msg):
    print msg
    return HttpResponse(resp_txt(msg, HELP_INFO))

def resp_disp_link(msg):
    print msg
    return HttpResponse(resp_txt(msg, HELP_INFO))


def resp_txt(msg, content):
    return TEXT_MSG_TPL % (msg['FromUserName'], msg['ToUserName'], str(int(time.time())), content)

def resp_articles(msg, articlelist):
    resp_head = NEWS_MSG_HEADER_TPL % (msg['FromUserName'], msg['ToUserName'], str(int(time.time())), len(articlelist))
    art_list = []
    for art in articlelist:
        art_xml = NEWS_MSG_ITEM_TPL % (art.get('title',''), art.get('description',''), art.get('picurl',''), art.get('url',''))
        art_list.append(art_xml)
    reply_xml = ''.join([resp_head, ''.join(art_list), NEWS_MSG_TAIL_TPL])
    return reply_xml
